package com.yanyeori.framework.redis.config;

import com.yanyeori.framework.core.interfaces.PublishEventUtil;
import com.yanyeori.framework.redis.configprop.RedisConfigProps;
import com.yanyeori.framework.redis.listener.RemoteEventListener;
import com.yanyeori.framework.redis.serializer.JacksonSerializer;
import com.yanyeori.framework.redis.util.RedisPublishEventUtil;
import com.yanyeori.framework.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Import;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

/**
 * Redis自动配置
 *
 * @author chenkuan 2020/8/14
 */
@Slf4j
@Configuration
@EnableConfigurationProperties({RedisConfigProps.class})
@Import({ConfigFactory.class, RedisLockConfig.class})
public class RedisAutoConfig {

    @Bean
    @ConditionalOnMissingBean(name = "redisTemplate")
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> redisTemplate = new RedisTemplate<>();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        //key的序列化方式:string
        redisTemplate.setKeySerializer(StringRedisSerializer.UTF_8);
        redisTemplate.setHashKeySerializer(StringRedisSerializer.UTF_8);
        //value的序列化:jackson
        redisTemplate.setValueSerializer(JacksonSerializer.serializer());
        redisTemplate.setHashValueSerializer(JacksonSerializer.serializer());
        //刷新设置
        redisTemplate.afterPropertiesSet();
        log.debug("RedisTemplate<String, Object> registered successfully");
        return redisTemplate;
    }

    @Bean
    @ConditionalOnMissingBean(name = "redisUtil")
    public RedisUtil redisUtil(RedisTemplate<String, Object> redisTemplate) {
        return new RedisUtil(redisTemplate);
    }

    @Bean
    public RemoteEventListener remoteEventListener() {
        return new RemoteEventListener();
    }

    @Bean
    @ConditionalOnMissingBean(PublishEventUtil.class)
    public PublishEventUtil redisPublishEventUtil(RedisTemplate<String, Object> redisTemplate) {
        return new RedisPublishEventUtil(redisTemplate);
    }
}
